/**
 * 配置表单组件
 * 用于管理应用的API和交易所配置
 * 使用localStorage进行配置的本地存储
 */
import React, { useState, useEffect } from 'react';
import { Form, Input, InputNumber, Select, Button, message, Collapse, notification, Typography } from 'antd';
import type { ExchangeBody, ApiConfig } from '../types';
import { ConfigManager } from '../services/ConfigManager';

const { Text } = Typography;

interface ConfigFormProps {
  visible: boolean;
  onCancel: () => void;
  onConfigUpdate: () => void;
}

const { Option } = Select;

/**
 * 配置表单组件
 * @param {ConfigFormProps} props - 组件属性
 * @returns {JSX.Element} 配置表单组件
 */
const ConfigForm: React.FC<ConfigFormProps> = ({ visible, onCancel, onConfigUpdate }) => {
  const [form] = Form.useForm();
  const [apiToken, setApiToken] = useState('KQBXL1S7R6B1Q152Z3F527L5'); // 默认API令牌
  const [loading, setLoading] = useState(false);
  const [activePanelKeys, setActivePanelKeys] = useState<string[]>([]); // 折叠面板的激活状态

  /**
   * 组件挂载时加载配置
   * 从localStorage加载保存的配置到表单中
   */
  useEffect(() => {
    console.log('ConfigForm: 组件挂载，开始加载配置...');
    
    // 立即设置表单默认值作为回退
    form.setFieldsValue({
      apiToken: 'KQBXL1S7R6B1Q152Z3F527L5',
      pageIndex: 1,
      resType: 0,
      platforms: 'BUFF-YYYP',
      sortBy: 1,
      minPrice: 1,
      maxPrice: 5000,
      searchText: '',
      turnover: undefined,
      buyOption: undefined
    });
    
    // 从localStorage加载保存的配置
    const loadSavedConfig = () => {
      try {
        console.log('ConfigForm: 开始从ConfigManager加载保存的配置...');
        
        // 加载API配置
        const apiConfig = ConfigManager.loadApiConfig();
        if (apiConfig?.apiToken) {
          console.log('ConfigForm: 成功加载API配置');
          setApiToken(apiConfig.apiToken);
          form.setFieldValue('apiToken', apiConfig.apiToken);
        }
        
        // 加载Exchange配置
        const exchangeConfig = ConfigManager.loadExchangeConfig();
        if (exchangeConfig) {
          console.log('ConfigForm: 成功加载Exchange配置');
          
          // 单独更新每个字段，避免覆盖未定义的值
          if (exchangeConfig.page_index !== undefined) form.setFieldValue('pageIndex', exchangeConfig.page_index);
          if (exchangeConfig.res !== undefined) form.setFieldValue('resType', exchangeConfig.res);
          if (exchangeConfig.platforms) form.setFieldValue('platforms', exchangeConfig.platforms);
          if (exchangeConfig.sort_by !== undefined) form.setFieldValue('sortBy', exchangeConfig.sort_by);
          if (exchangeConfig.min_price !== undefined) form.setFieldValue('minPrice', exchangeConfig.min_price);
          if (exchangeConfig.max_price !== undefined) form.setFieldValue('maxPrice', exchangeConfig.max_price);
          if (exchangeConfig.text) form.setFieldValue('searchText', exchangeConfig.text);
          if (exchangeConfig.turnover !== undefined) form.setFieldValue('turnover', exchangeConfig.turnover);
          if (exchangeConfig.buy !== undefined) form.setFieldValue('buyOption', exchangeConfig.buy);
        }
        
        console.log('ConfigForm: 配置加载完成');
      } catch (error) {
        console.error('ConfigForm: 加载配置时发生错误:', error);
        // 出错时保持已设置的默认值
      }
    };
    
    loadSavedConfig();
  }, [form]);

  /**
   * 当visible改变时，确保表单值设置正确
   */
  useEffect(() => {
    if (visible) {
      // 确保表单始终有有效值
      form.setFieldsValue({
        apiToken: form.getFieldValue('apiToken') || 'KQBXL1S7R6B1Q152Z3F527L5',
        pageIndex: form.getFieldValue('pageIndex') || 1
      });
    }
  }, [visible, form]);

  /**
   * 实时同步保存配置变更到localStorage
   * @param {any} _changedValues - 变更的表单值
   * @param {any} allValues - 当前所有表单值
   */
  const handleValuesChange = (_changedValues: Record<string, unknown>, allValues: Record<string, unknown>) => {
    try {
      // 构建配置对象，确保所有必要字段都有默认值
      const exchangeBody: ExchangeBody = {
        // 严格按照接口定义设置所有字段
        buy: typeof allValues.buyOption === 'number' ? allValues.buyOption : undefined,
        max_price: typeof allValues.maxPrice === 'number' ? allValues.maxPrice : undefined,
        min_price: typeof allValues.minPrice === 'number' ? allValues.minPrice : undefined,
        page_index: typeof allValues.pageIndex === 'number' ? allValues.pageIndex : 1,
        platforms: (typeof allValues.platforms === 'string' && ['BUFF-YYYP', 'BUFF', 'YYYP'].includes(allValues.platforms)) ? allValues.platforms as 'BUFF-YYYP' | 'BUFF' | 'YYYP' : 'BUFF-YYYP',
        res: typeof allValues.resType === 'number' ? allValues.resType : 0,
        sort_by: typeof allValues.sortBy === 'number' ? allValues.sortBy : 1,
        // 确保可选字段也被正确设置
        text: typeof allValues.searchText === 'string' ? allValues.searchText : undefined,
        turnover: typeof allValues.turnover === 'number' ? allValues.turnover : undefined,
      };
      
      console.log('ConfigForm: 构建完整exchange配置:', exchangeBody);

      // 构建API配置对象
      const apiConfig: ApiConfig = {
        apiToken: typeof allValues.apiToken === 'string' ? allValues.apiToken : (apiToken || 'KQBXL1S7R6B1Q152Z3F527L5')
      };
      
      // 验证必要字段都已存在（根据types.ts定义，min_price和max_price是可选字段）
      if (exchangeBody.page_index === undefined || 
          exchangeBody.res === undefined || 
          !exchangeBody.platforms || 
          exchangeBody.sort_by === undefined) {
        console.error('ConfigForm: 必要字段缺失，跳过保存', exchangeBody);
        return;
      }
      
      // 立即保存配置到localStorage
      const apiSaved = ConfigManager.saveApiConfig(apiConfig);
      const exchangeSaved = ConfigManager.saveExchangeConfig(exchangeBody);

      if (apiSaved && exchangeSaved) {
        // 更新本地状态
        setApiToken(apiConfig.apiToken);
        
        // 通知父组件配置已更新
        onConfigUpdate();
        
        // 静默保存，不显示通知避免干扰用户体验
        console.log('ConfigForm: 配置已实时保存');
      } else {
        console.warn('ConfigForm: 配置保存未完全成功');
        // 保存失败时显示错误通知
        notification.error({
          message: '配置保存失败',
          placement: 'topRight',
          duration: 2
        });
      }
    } catch (error) {
      console.error('ConfigForm: 保存配置失败:', error);
      notification.error({
        message: '配置保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        placement: 'topRight',
        duration: 3
      });
    }
  };
  
  /**
   * 保存配置按钮的处理函数（保留以兼容表单提交，但实际配置已实现实时保存）
   */
  const handleSave = () => {
    try {
      setLoading(true);
      const values = form.getFieldsValue();
      
      // 构建配置对象
      const exchangeBody: ExchangeBody = {
        page_index: values.pageIndex,
        res: values.resType,
        platforms: values.platforms,
        sort_by: values.sortBy,
        min_price: values.minPrice,
        max_price: values.maxPrice,
        text: values.searchText || undefined,
        turnover: values.turnover || undefined,
        buy: values.buyOption || undefined
      };

      // 构建API配置对象
      const apiConfig: ApiConfig = {
        apiToken: values.apiToken || apiToken
      };
      
      // 保存配置到localStorage
      const apiSaved = ConfigManager.saveApiConfig(apiConfig);
      const exchangeSaved = ConfigManager.saveExchangeConfig(exchangeBody);

      if (apiSaved && exchangeSaved) {
        message.success('配置保存成功');
        setApiToken(apiConfig.apiToken);
      } else {
        message.error('配置保存失败');
      }
    } catch (error) {
      console.error('保存配置失败:', error);
      message.error('保存配置失败');
    } finally {
      setLoading(false);
    }
  };
  
  /**
   * 处理折叠面板状态变化
   * @param {string | string[]} keys - 折叠面板的激活键
   */
  const handlePanelChange = (keys: string | string[]) => {
    setActivePanelKeys(keys as string[]);
  };

  /**
   * 显示调试信息通知
   */
  const handleShowDebugInfo = () => {
    notification.info({
      message: '调试信息已输出到控制台',
      description: '请查看浏览器开发者工具的控制台标签页',
      placement: 'topRight',
      duration: 3
    });
  };

  return (
    <div style={{ padding: '8px 16px', backgroundColor: '#f5f5f5', display: 'flex', justifyContent: 'center' }}>
      <div style={{ width: '100%', maxWidth: '800px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px', marginTop: '4px' }}>
          <h3 style={{ color: '#333', margin: 0 }}>配置设置</h3>
          <Button size="small" onClick={handleShowDebugInfo} type="link">
            <Text type="secondary">调试信息</Text>
          </Button>
        </div>
        <Form
          form={form}
          layout="horizontal"
          onFinish={handleSave}
          onValuesChange={handleValuesChange}
          initialValues={{
            pageIndex: 1,
            resType: 0,
            platforms: 'BUFF-YYYP',
            sortBy: 1,
            minPrice: 1,
            maxPrice: 5000
            // apiToken 从配置文件加载，不在initialValues中设置
          }}
          style={{ margin: '0 auto' }}
      >
        <Form.Item label="获取结果类型" name="resType" rules={[{ required: true, message: '请选择结果类型' }]}>
          <Select placeholder="选择获取结果类型">
            <Option value={0}>Steam余额（挂刀）</Option>
            <Option value={1}>平台余额（反向挂刀）</Option>
          </Select>
        </Form.Item>

        <Form.Item label="平台选择" name="platforms" rules={[{ required: true, message: '请选择平台' }]}>
          <Select placeholder="选择交易平台">
            <Option value="BUFF-YYYP">BUFF和悠悠有品</Option>
            <Option value="BUFF">仅BUFF</Option>
            <Option value="YYYP">仅悠悠有品</Option>
          </Select>
        </Form.Item>

        <Form.Item label="出售方案选择" name="sortBy" rules={[{ required: true, message: '请选择出售方案' }]}>
          <Select placeholder="选择出售方案">
            <Option value={0}>在售价首先（Steam挂底价出售）</Option>
            <Option value={1}>求购价优先（Steam丢求购出售）</Option>
          </Select>
        </Form.Item>

        <Form.Item label="价格范围">
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', width: '100%' }}>
            <Form.Item name="minPrice" noStyle>
              <InputNumber min={0} style={{ width: '45%' }} placeholder="最低" />
            </Form.Item>
            <span>至</span>
            <Form.Item name="maxPrice" noStyle>
              <InputNumber min={0} style={{ width: '45%' }} placeholder="最高" />
            </Form.Item>
          </div>
        </Form.Item>

        {/* 搜索关键字已移至列表上方 */}

        <Form.Item label="Steam日成交量" name="turnover">
          <InputNumber min={0} style={{ width: '100%' }} placeholder="筛选大于等于该日成交量" />
        </Form.Item>

        <Form.Item label="购买方案选择" name="buyOption">
          <Select placeholder="仅反向挂刀时需要设置">
            <Option value={0}>在售价首先（从Steam在售底价购买）</Option>
            <Option value={1}>求购价优先（从Steam挂求购购买）</Option>
          </Select>
        </Form.Item>

        {/* 使用折叠面板显示基础设置，默认折叠 */}
        <Collapse 
          activeKey={activePanelKeys} 
          onChange={handlePanelChange}
          style={{ marginBottom: '8px' }}
          items={[
            {
              key: '1',
              label: '基础设置',
              children: (
                <>
                  <Form.Item label="API Token" name="apiToken">
                    <Input placeholder="请输入CSQAQ API Token" />
                  </Form.Item>

                  <Form.Item label="当前页码" name="pageIndex" rules={[{ required: true, message: '请输入页码' }]}>
                    <InputNumber min={1} style={{ width: '100%' }} />
                  </Form.Item>
                </>
              )
            }
          ]}
        />
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} disabled>
            配置已自动保存
          </Button>
        </Form.Item>
      </Form>
      </div>
    </div>
  );
};

export default ConfigForm;